package com.baofu.paycore.service.validate.account;

import com.baofu.paycore.common.enums.RedisKeyEnum;
import com.baofu.paycore.common.exception.ValidateException;
import com.baofu.paycore.common.utils.RedisKeyUtil;
import com.baofu.paycore.manager.cache.RedisManager;
import com.baofu.paycore.manager.model.FreezeBO;
import com.baofu.paycore.manager.model.PayBaseBO;
import com.baofu.paycore.manager.storer.FreezeOrderRepository;
import com.baofu.paycore.manager.storer.OrderRepository;
import com.baofu.paycore.service.facade.enums.PayCoreErrorCode;
import com.baofu.paycore.service.facade.enums.PayStatusEnums;
import com.baofu.paycore.service.facade.model.AccountFreeze.FreezeDTO;
import com.baofu.paycore.service.facade.model.AccountFreeze.FreezeResDTO;
import com.baofu.paycore.service.facade.model.AccountFreeze.UnfreezeDTO;
import com.baofu.paycore.service.facade.model.withdraw.WithdrawResDTO;
import com.baofu.paycore.service.validate.AbstractPayValidate;
import com.system.commons.result.Result;
import com.system.commons.utils.BeanCopyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * </p>
 * User:ames wang  Date: 2017/6/22
 */
@Slf4j
@Service
public class UnfreezeValidate extends AbstractPayValidate<UnfreezeDTO> {

    @Autowired
    private FreezeOrderRepository freezeOrderRepository;

    /**
     * redis服务
     */
    @Autowired
    private RedisManager redisManager;

    /**
     * 解冻提现参数校验
     *
     * @param t     被校验对象
     */
    public void paramsValidate(UnfreezeDTO t) {
        super.paramsValidate(t);
        FreezeBO freezeBO = freezeOrderRepository.load(t.getOrigPayNo());
        if (freezeBO == null) {
            log.error("冻结订单不存在,:{}", t.getOrigPayNo());
            throw new ValidateException(PayCoreErrorCode.OLD_ORDER_IS_NOT_EXISTED);
        } else {
            redisManager.insertObject(freezeBO,
                    RedisKeyUtil.buildRedisKey(RedisKeyEnum.PAY_ACC_UNFREEZE, t.getOrigPayNo()));
        }
    }

    /**
     * 订单唯一性校验
     *
     * @param t     被校验对象
     */
    public Result<WithdrawResDTO> validateUniqueOrder(UnfreezeDTO t, OrderRepository orderRepository){
        PayBaseBO order = orderRepository.checkIdempotent(t.getRequestBizNo(),t.getRequestOrderNo(),t.getRequestSystem());
        if(order != null){
            WithdrawResDTO withdrawResDTO=BeanCopyUtil.objConvert(order,WithdrawResDTO.class);
            withdrawResDTO.setRealRtnFlag(Boolean.TRUE);
            withdrawResDTO.setRespDate(order.getUpdatedAt());
            return new Result<>(withdrawResDTO);
        }
        return null;
    }
}
